#!/usr/bin/python3
# -*- coding: UTF-8 -*-

from auto_report.auto_report import AutoReport
import os
from openpyxl import load_workbook
from auto_report.utils import info, warning, read_from_xlsx, get_font
from rich import print
import shutil
from openpyxl.utils.cell import coordinate_from_string


THREE_LAKE_VALUE_MAP = {
    '抚仙湖': 'A7:BH15',
    '杞麓湖': 'A16:BH26',
    '星云湖': 'A27:BH45',
}

TARGET_AREA = 'A7:BH45'

PRIMARY_COL = 3
MOD_START_COL = 14
MOD_END_COL = 59


TEXT_RED_16 = get_font('ff0000', 16)
TEXT_BLACK_16 = get_font('000000', 16)


class LakeReport(AutoReport):
    """docstring for LakeReport"""

    def __init__(self, target_month):
        super(LakeReport, self).__init__(target_month)
        self.target_month = target_month
        self.report_name = '云南省“双十”重大工程（九大高原湖泊流域生态保护与修复工程）项目进展情况表'

    def get_src_file(self):
        return f'玉溪市-{self.get_last_month_field()}-{self.report_name}.xlsx'

    def get_dst_file(self):
        return f'玉溪市-{self.get_month_field()}-{self.report_name}.xlsx'

    def generate(self):
        src_file = self.get_src_file() if os.path.exists(
            self.get_src_file()) else f'{self.report_name}.xlsx'

        target_wb = load_workbook(src_file)
        target_ws = target_wb.active

        src_folder = f'jiuhu/{self.target_month}'
        files = self.get_files(src_folder)
        for f in files:
            incoming_data = read_from_xlsx(f'{src_folder}/{f}', row_offset=6)
            info(f'数据行数：{len(incoming_data)}')
            lake_name = incoming_data[0][0] if len(
                incoming_data) > 0 and incoming_data[0][0] else ''
            name = str(lake_name).replace('\n', '')
            if not name in THREE_LAKE_VALUE_MAP:
                continue
            info('处理', name)
            # self.sumary(f'{self.folder}/{f}')

            one_lake_mod_area = target_ws[THREE_LAKE_VALUE_MAP.get(name)]
            for rowIndex, r in enumerate(one_lake_mod_area):
                if r[PRIMARY_COL].value == incoming_data[rowIndex][PRIMARY_COL]:
                    for colIndex in range(MOD_START_COL, MOD_END_COL):
                        newVal = incoming_data[rowIndex][colIndex]
                        if r[colIndex].value != newVal:
                            warning(
                                f'修改 {r[colIndex].coordinate}, {r[colIndex].value} -> {newVal}')
                            r[colIndex].value = newVal
                            r[colIndex].font = TEXT_RED_16
                        else:
                            r[colIndex].font = TEXT_BLACK_16

        dst_file = self.get_dst_file()
        target_ws['B2'].value = f'{self.report_name}（{self.get_month_field()}）'
        target_wb.save(dst_file)

        print('完成', dst_file)

    def split(self):
        split_file = self.get_dst_file() if os.path.exists(
            self.get_dst_file()) else None
        if (split_file == None):
            warning('错误！找不到文件', self.dst_file)
            return
        info('拆分', split_file)
        target_dir = 'dst'
        if os.path.exists(target_dir):
            shutil.rmtree(target_dir)
        os.mkdir(target_dir)

        from_wb = load_workbook(split_file)
        all_row_start = coordinate_from_string(
            TARGET_AREA.split(':')[0])[1]  # 7
        all_row_end = coordinate_from_string(
            TARGET_AREA.split(':')[1])[1]  # 39
        info('all row', all_row_start, all_row_end)
        lakes = set(THREE_LAKE_VALUE_MAP.keys())

        for index, key in enumerate(lakes):
            one_lake_file = f'{target_dir}/{index}-{key}-{self.get_month_field()}-{self.report_name}.xlsx'
            from_wb.save(one_lake_file)

            info('处理', one_lake_file)
            start_row = coordinate_from_string(
                THREE_LAKE_VALUE_MAP.get(key).split(':')[0])[1]
            end_row = coordinate_from_string(
                THREE_LAKE_VALUE_MAP.get(key).split(':')[1])[1]
            info(start_row, end_row)

            row_num = end_row - start_row
            before_range = (all_row_start, start_row-all_row_start)
            after_range = (end_row+1, all_row_end-end_row)
            info(before_range, after_range)

            new_wb = load_workbook(one_lake_file)
            new_ws = new_wb.active

            unmerge_list = []
            for mcr in new_ws.merged_cells:
                if mcr.min_row > 6 and mcr.max_col < 3:
                    unmerge_list.append(mcr.coord)
            print(unmerge_list)
            for area in unmerge_list:
                new_ws.unmerge_cells(area)
            new_wb.save(one_lake_file)

            new_wb = load_workbook(one_lake_file)
            new_ws = new_wb.active

            if after_range[1] > 0:
                new_ws.delete_rows(after_range[0], after_range[1])
            if before_range[1] > 0:
                new_ws.delete_rows(before_range[0], before_range[1])

            new_wb.save(one_lake_file)

            new_wb = load_workbook(one_lake_file)
            new_ws = new_wb.active

            one_lake_mod_area = new_ws[TARGET_AREA]
            for _, r in enumerate(one_lake_mod_area):
                for colIndex in range(MOD_START_COL, MOD_END_COL):
                    r[colIndex].font = TEXT_BLACK_16
            for _, r in enumerate(one_lake_mod_area):
                for colIndex in range(MOD_START_COL, MOD_END_COL):
                    r[colIndex].font = TEXT_BLACK_16
            new_ws.merge_cells(f'A7:A{7 + row_num}')
            new_ws.merge_cells(f'B7:B{7 + row_num}')

            for i in range(7+row_num+1, all_row_end+1):
                new_ws.row_dimensions[i].height= 18

            new_wb.save(one_lake_file)

        info('完成')
